$(function () {
    // loadKeyWords();
    loadTable();
});
var table;

function loadKeyWords() {
    var url = baseQuestionUrl + "list/unanswered?start=0&limit=1000000";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        type: "GET",
        contentType: "application/json",
        success: function (data) {
            loadTable(data.data.rows);
        }
    }));

}

function loadTable(data) {
    var jishuji=0;
    table = $("#keyWordsTable").DataTable({
        ajax: {
            url: baseQuestionUrl + "list/unanswered",
            headers: {
                "authorization": 'Bearer ' + getCookie(cookieName)
            },
            type: "GET",
            contentType: "application/json",
            data: function (req) {
                req.limit = req.length;
                req.search = req.search.value;
            },
            dataSrc: function (res) {
                if(res.code===200&&res.data) {
                    res.recordsTotal = res.data.total;
                    res.recordsFiltered = res.data.total;
                    jishuji = 0;
                    return res.data.rows;
                }
            },
            error: function (request, error) {
                if (request.status === 401) {
                    $(location).attr('href', 'login.html');
                } else {
                    swal("失败");
                }
            }
        },
        serverSide: true,
        bLengthChange: false,
        // data: data,
        // destroy: true,
        searching: true,
        ordering: false,
        select: true,
        columns: [
            {data: ''},

            {data: ''},
        ],
        pagingType: "full_numbers",
        language: {
            sProcessing: "处理中...",
            sLengthMenu: "显示 _MENU_ 项结果",
            sZeroRecords: "没有匹配结果",
            sInfo: "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            sInfoEmpty: "显示第 0 至 0 项结果，共 0 项",
            sInfoFiltered: "(由 _MAX_ 项结果过滤)",
            sInfoPostFix: "",
            sSearch: "搜索:",
            sUrl: "",
            sEmptyTable: "表中数据为空",
            sLoadingRecords: "载入中...",
            sInfoThousands: ",",
            oPaginate: {
                sFirst: "首页",
                sPrevious: "上页",
                sNext: "下页",
                sLast: "末页"
            },
            oAria: {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        },

        columnDefs: [
            // {orderable: false, targets: 0},

            {

                targets: 1,
                render: function (data, type, row, meta) {

                    return "<div name='disp' id='disp"+row.id+"'>"+row.unanswered+"</div><textarea name='greet' id='unanswered"+row.id+"' rows='3'  style='width:600px;ertical-align:top;display:none;'>";
                }

            },
            {

                targets: 0,
                render: function (data, type, row, meta) {
                    jishuji=jishuji+1;
                    return jishuji;

                }

            },
            {

                targets: 2,
                render: function (data, type, row, meta) {
                    var time = new Date(row.updated);
                    var y = time.getFullYear();
                    var m = time.getMonth()+1;
                    var d = time.getDate();
                    var h = time.getHours();
                    var mm = time.getMinutes();
                    var s = time.getSeconds();
                    return y+'-'+m+'-'+d+' '+h+':'+mm+':'+s;
                }

            },
            {
                targets: 3,
                render: function (data, type, row, meta) {
                    return "<button name='a' id='a"+row.id+"' type='button' style='margin-right: 10px;border: 1px solid #0D1113;color: #0D1113;background: transparent;'  class='btn btn-primary' onclick='deleteQuestion1(" + JSON.stringify(row) +");'>编辑</button><button name='b' id='b"+row.id+"'type='button' style='display:none;margin-right: 10px;border: 1px solid #0D1113;color: #0D1113;background: transparent;' class='btn btn-primary' onclick='updateKeyWord(" + JSON.stringify(row) +");'>确定</button><button name='b' id='c"+row.id+"'  type='button' style='display:none;margin-right: 10px;border: 1px solid #0D1113;color: #0D1113;background: transparent;' class='btn btn-primary' onclick='quxiaoanniu(" + JSON.stringify(row) +")'>取消</button><button name='a'  id='d"+row.id+"'  type='button' class='btn btn-danger' style='margin-right: 10px;border: 1px solid red;color: red;background: transparent;' onclick='deleteQuestion(" + JSON.stringify(row) + ");'>删除</button>";

                }
            }]
    });
}

/**
 * 新增问候语
 */
function xinzenwenhou(woshizhu) {
    var data = {"keyWord": woshizhu};
    var url = baseQuestionUrl + "add/unanswered";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        data: JSON.stringify(data),
        type: "POST",
        contentType: "application/json",
        success: function (data) {
            if (!data.data) {
                swal("新增失败",'','error');
            } else {
                swal('新增成功','','success');
                $('#deleteModal2').modal('hide');
                table.ajax.reload();
            }
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
            }
        }
    }));
    $('#unanswered').val("")
}

function showDelete(keyWord) {
    $("#id").text(keyWord.id);
    $('#deleteModal').modal('show');
}

/*
* 编辑问候语
* */
function updateKeyWord(wenhou){

    url = baseQuestionUrl + "update2";
    var woshizhu= $("#unanswered"+wenhou.id).val();
    var unanswered = new Unanswered(wenhou.id, woshizhu);
    var data = JSON.stringify(unanswered);
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        type: "POST",
        data: data,
        contentType: "application/json",
        success: function (data) {
            if (!data.data) {
                swal("修改失败",'','error');
            } else {
                swal('修改成功','','success');
                table.ajax.reload();
            }
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
            }
        }
    }));
}
/**
 * 删除一个未启用的关键字
 * @param id
 */
function deleteKeyWord(id) {
    var url = baseQuestionUrl + "delete2/" + id;
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        type: "DELETE",
        contentType: "application/json",
        success: function () {
            swal("删除！", "当前记录已被删除！", "success");
            table.ajax.reload();
            // $('#deleteModal').modal('hide');
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
                $('#deleteModal').modal('hide');
            }
        }
    }));
}
function deleteQuestion(question) {
    swal({
            title: "删除未匹配问题",
            text: "确认要删除未匹配问题？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#337ab7",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: false,
            closeOnCancel: true
        },
        function(isConfirm){
            if (isConfirm) {
                var url = baseQuestionUrl + "delete2/" + question.id;
                ajaxCommon.request('delete',url,{},function (res) {
                    if(res.code===200) {
                        swal("删除！", "当前记录已被删除！", "success");
                        table.ajax.reload();
                    }
                    // $('#deleteModal').modal('hide');
                })
            }
        });
}
function deleteQuestion1(question) {
    $("button[name*='a']").show();
    $("button[name*='b']").hide();
    $("#b"+question.id).show();
    $("#c"+question.id).show();;
    $("#d"+question.id).hide();
    $("#a"+question.id).hide();
    $("textarea[name*='greet']").hide();
    $("div[name*='disp']").show();
    $("#unanswered"+question.id).show();
    $("#unanswered"+question.id).val(question.unanswered);
    $("#disp"+question.id).hide();
}
function addQuestion() {
    $('#greetings').val('')
    $('#deleteModal2').modal('toggle');
}
/*页面取消*/
function  quxiaoanniu(question){
    $("#b"+question.id).hide();
    $("#c"+question.id).hide();
    $("#d"+question.id).show()
    $("#a"+question.id).show()
    $("#unanswered"+question.id).hide();
    $("#unanswered"+question.id).val(question.unanswered);
    $("#disp"+question.id).show();

}
